<template>
  <div class="app-container">
    <!-- <el-row :gutter="20"> -->
    <!--部门数据-->
    <!-- <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入部门名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col> -->
    <!--用户数据-->
    <!-- <el-col :span="24" :xs="24"> -->
    <!-- <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="对话标题" prop="topic">
        <el-input
          v-model="queryParams.topic"
          placeholder="请输入用户名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form> -->

    <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="!multiple"
          @click="handleDelete"
          v-hasPermi="['system:chat:remove']"
          >删除</el-button
        >
      </el-col>
    </el-row> -->

    <el-table
      v-loading="loading"
      :data="dataList"
      row-key="topic_id"
      ref="tables"
      :tree-props="{ children: 'children' }"
    >
      <!-- <el-table-column width="120" align="left">
        <template #header>
          <el-checkbox
            v-model="selectAll"
            :checked="selectAll"
            :indeterminate="isIndeterminate"
            @change="setCheckAll"
          />
          {{ selectionName }}
        </template>

        <template #default="scope">
          <el-checkbox
            v-model="scope.row[selectionConfig.checked]"
            :checked="scope.row[selectionConfig.checked]"
            :indeterminate="scope.row[selectionConfig.indeterminate]"
            :disabled="scope.row[selectionConfig.disabled]"
            @change="setCheck(scope.row)"
          />
        </template>
      </el-table-column> -->

      <!-- <el-table-column type="selection"
                       width="50"
                       align="center" /> -->
      <el-table-column label="序号" align="center" key="id" prop="id">
        <template #default="scope">
          <div class="link"  @click="toChatPage(scope.row.id)"
            >{{ scope.row.id }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="对话标题"
        align="center"
        key="title"
        prop="title"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="类型"
        align="center"
        key="type"
        prop="type"
        :show-overflow-tooltip="true"
      />

      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="160"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        width="160"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="160"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:chat:remove']"
            >删除</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit-outline"
            @click="showConversationsRename(scope.row)"
            v-hasPermi="['system:chat:remove']"
            >重命名</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- </el-col>
    </el-row> -->

    <el-dialog
      title="对话名称重命名"
      :visible.sync="conversationsRenameOpen"
      width="500px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="原对话名称" prop="configName">
          {{ row.name }}
        </el-form-item>
        <el-form-item label="新对话名称" prop="configName">
          <el-input
            v-model="newConversationName"
            placeholder="请输入新对话名称"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="conversationsRename">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style scoped lang="scss">
.link {
  color: #167dd7;
  cursor: pointer;
}
</style>
<script>
import {
  listUser,
  getUser,
  delUser,
  addUser,
  updateUser,
  resetUserPwd,
  changeUserStatus,
} from "@/api/system/user";
import { getToken } from "@/utils/auth";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {
  getchattopiclist,
  deletechattopic,
  deletechatdetail,
} from "@/api/chat";
import {
  conversations,
  messages,
  upload,
  delconversations,
  conversationsRename,
} from "@/api/ai";
import { deepClone, formatDate } from "@/utils";
import { mapGetters, mapActions } from "vuex";
export default {
  name: "User",
  dicts: ["sys_normal_disable", "sys_user_sex"],
  components: { Treeselect },
  data() {
    return {
      row: {},
      newConversationName: "",
      conversationsRenameOpen: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      dataList: [],
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        topic: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined,
      },
      // 列信息
      columns: [
        { key: 0, label: `用户编号`, visible: true },
        { key: 1, label: `用户名称`, visible: true },
        { key: 2, label: `用户昵称`, visible: true },
        { key: 3, label: `部门`, visible: true },
        { key: 4, label: `手机号码`, visible: true },
        { key: 5, label: `状态`, visible: true },
        { key: 6, label: `创建时间`, visible: true },
      ],
      // 表单校验
      rules: {
        topic: [
          { required: true, message: "用户名称不能为空", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "用户名称长度必须介于 2 和 20 之间",
            trigger: "blur",
          },
        ],
        nickName: [
          { required: true, message: "用户昵称不能为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "用户密码不能为空", trigger: "blur" },
          {
            min: 5,
            max: 20,
            message: "用户密码长度必须介于 5 和 20 之间",
            trigger: "blur",
          },
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        phonenumber: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
      },
      selectionName: "",
      selectAll: false, // 全选
      isIndeterminate: false, // 半选
      selectionConfig: {
        checked: "checked",
        indeterminate: "indeterminate",
        disabled: "disabled",
      },
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
  },
  computed: {
    ...mapGetters([
      "name",
      "sidebar",
      "device",
      "avatar",
      "chatList",
      "currentTopicId",
      "chatfromdify",
    ]),
  },
  created() {
    this.getList();
    // this.getTreeselect();
    // this.getConfigKey("sys.user.initPassword").then(response => {
    //   this.initPassword = response.msg;
    // });
  },
  methods: {
    ...mapActions("chat", ["getchattopic"]),
    showConversationsRename(row) {
      this.row = row;
      this.newConversationName = "";
      this.conversationsRenameOpen = true;
    },
    toChatPage(id) {
      this.$router.push({ path: "/index", query: { id } });
    },
    getAllIds(tree, childresult, parentresult, parentId, ischildnode) {
      //遍历树  获取id数组
      let checknode = 0;
      for (const i in tree) {
        if (tree[i]["checked"] && ischildnode) {
          childresult.push(tree[i]["topic_id"]); // 遍历项目满足条件后的操作
          checknode++;
        }
        if (tree[i].children) {
          //存在子节点就递归
          this.getAllIds(
            tree[i].children,
            childresult,
            parentresult,
            tree[i]["topic_id"],
            true
          );
        }
      }

      if (ischildnode && checknode === tree.length) {
        parentresult.push(parentId);
      }
      return { childresult, parentresult };
    },
    // 全选
    setCheckAll() {
      this.dataList.forEach((item) => {
        if (!item[this.selectionConfig.disabled]) {
          item[this.selectionConfig.checked] = this.selectAll;
        }
        this.setChildren(item, this.selectAll);
      });
      this.isIndeterminate = false;
      let { childresult, parentresult } = this.getAllIds(
        this.dataList,
        [],
        [],
        ""
      );
    },
    // 单选
    setCheck(row) {
      // 设置该单元格所有子节点状态
      this.setChildren(row, row[this.selectionConfig.checked]);
      let result = this.setParentCheck(row);
      // 遍历到顶级，顶级无父节点，判断顶级节点是否都为选中
      if (!result) {
        let isAll = this.dataList.every((item) => {
          return item[this.selectionConfig.checked];
        });
        this.selectAll = isAll;

        if (isAll) {
          this.isIndeterminate = false;
        } else {
          let isIndeterminate = this.dataList.some((item) => {
            return (
              item[this.selectionConfig.checked] ||
              item[this.selectionConfig.indeterminate]
            );
          });
          this.isIndeterminate = isIndeterminate;
        }
      }
      let { childresult, parentresult } = this.getAllIds(
        this.dataList,
        [],
        [],
        ""
      );
    },
    // 设置子节点
    setChildren(row, checked) {
      row[this.selectionConfig.indeterminate] = false;

      if (row["children"]) {
        row["children"].forEach((item) => {
          if (!item[this.selectionConfig.disabled]) {
            item[this.selectionConfig.checked] = checked;
            item[this.selectionConfig.indeterminate] = false;
          }
          if (row["children"]) {
            this.setChildren(item, checked);
          }
        });
      }
    },
    // 设置父节点
    setParentCheck(row) {
      // 寻找该行数据的父节点
      let parent = null;
      for (let i = 0; i < this.dataList.length; i++) {
        parent = this.findItem(this.dataList[i], row.parent_id);
        if (parent != null) {
          break;
        }
      }
      // 遍历该行的父节点下，所有的子节点
      if (parent != null) {
        if (parent["children"]) {
          // 子节点是否全都选中，如果是则则勾选该节点
          let isAll = parent["children"].every((item) => {
            return item[this.selectionConfig.checked];
          });

          parent[this.selectionConfig.checked] = isAll;
          if (isAll) {
            parent[this.selectionConfig.indeterminate] = false;
          } else {
            let isIndeterminate = parent["children"].some((item) => {
              return item[this.selectionConfig.checked];
            });
            parent[this.selectionConfig.checked] = isIndeterminate;
            parent[this.selectionConfig.indeterminate] = isIndeterminate;
          }

          // 递归查找该行父级的父级节点
          this.setParentCheck(parent, parent[this.selectionConfig.checked]);
        }
      } else {
        // 遍历到顶级，停止
        return null;
      }
    },
    // 查递归找该行的父节点
    findItem(row, id) {
      if (row.topic_id == id) {
        return row;
      }
      if (row["children"]) {
        let parent = null;
        for (let i = 0; i < row["children"].length; i++) {
          parent = this.findItem(row["children"][i], id);
          if (parent) {
            break;
          }
        }
        return parent;
      } else {
        return null;
      }
    },
    /** 查询用户列表 */
    async getList() {
      this.loading = true;
      let response;
      if (this.chatfromdify) {
        let data = {
          user: this.name,
          limit: 100,
        };

        // let str = qs.stringify(data);
        response = await conversations(data);
        response.data.forEach((item) => {
          item.title = item.name;
          item.createTime = formatDate(item.created_at * 1000);
          item.updateTime = formatDate(item.updated_at * 1000);
          item.type = item["inputs"]["Foucs"] === "general" ? "通用" : "学术";
        });
      } else {
        response = await getchattopiclist(
          this.addDateRange(this.queryParams, this.dateRange)
        );
      }

      let res = response.data;
      let DFS = function (tree) {
        tree.forEach((node) => {
          node.title = node.topic || node.title;
          node.children && DFS(node.children);
          (node.checked = false), (node.isItemIndeterminate = false);
        });
      };
      DFS(res);
      this.dataList = res;
      // this.total = response.total;
      this.loading = false;
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.handleQuery();
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal
        .confirm('确认要"' + text + '""' + row.topic + '"用户吗？')
        .then(function () {
          return changeUserStatus(row.userId, row.status);
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        deptId: undefined,
        topic: undefined,
        nickName: undefined,
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        sex: undefined,
        status: "0",
        remark: undefined,
        postIds: [],
        roleIds: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleResetPwd":
          this.handleResetPwd(row);
          break;
        case "handleAuthRole":
          this.handleAuthRole(row);
          break;
        default:
          break;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getTreeselect();
      getUser().then((response) => {
        this.postOptions = response.posts;
        this.roleOptions = response.roles;
        this.open = true;
        this.title = "添加用户";
        this.form.password = this.initPassword;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      const userId = row.userId || this.ids;
      getUser(userId).then((response) => {
        this.form = response.data;
        this.postOptions = response.posts;
        this.roleOptions = response.roles;
        this.form.postIds = response.postIds;
        this.form.roleIds = response.roleIds;
        this.open = true;
        this.title = "修改用户";
        this.form.password = "";
      });
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.topic + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
      })
        .then(({ value }) => {
          resetUserPwd(row.userId, value).then((response) => {
            this.$modal.msgSuccess("修改成功，新密码是：" + value);
          });
        })
        .catch(() => {});
    },
    /** 分配角色操作 */
    handleAuthRole: function (row) {
      const userId = row.userId;
      this.$router.push("/system/user-auth/role/" + userId);
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.userId != undefined) {
            updateUser(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUser(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    async conversationsRename() {
      console.log(this.row);
      if (this.row && this.row.id && this.newConversationName) {
        let res = await conversationsRename(
          { user: this.name, name: this.newConversationName },
          this.row.id
        );
        this.$message({
          message: "修改成功",
          type: "success",
        });
        this.conversationsRenameOpen = false;
        this.getList();
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      if (this.chatfromdify) {
        this.$modal
          .confirm("是否确认删除？")
          .then(async () => {
            let res = await delconversations({ user: this.name }, row.id);
            console.log(res);
            this.getList();
          })
          .catch(() => {});
      } else {
        this.$modal
          .confirm("是否确认删除？")
          .then(async () => {
            let { childresult, parentresult } = this.getAllIds(
              this.dataList,
              [],
              [],
              ""
            );
            let childresultIds = childresult.join(",");
            let parentresultIds = parentresult.join(",");
            if (childresultIds.length) {
              await deletechatdetail(childresultIds);
            }
            if (parentresult.length) {
              await deletechattopic(parentresultIds);
            }
          })
          .then(() => {
            this.getList();
            this.getchattopic();
            this.$modal.msgSuccess("删除成功");
          })
          .catch(() => {});
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/user/export",
        {
          ...this.queryParams,
        },
        `user_${new Date().getTime()}.xlsx`
      );
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "system/user/importTemplate",
        {},
        `user_template_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  },
};
</script>